<template>
  <xh-container btnText="保存" @onSave="handleClickSubmit" title="新增">
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item label="检验日期" name="inspectDate" required>
          <uni-datetime-picker
            type="date"
            v-model="formData.inspectDate"
            :start="Date.now()"
          />
        </uni-forms-item>
        <uni-forms-item label="检验类型" name="type" required>
          <uni-data-select
            v-model="formData.type"
            :localdata="typeOptions"
            @change="handleChangeType"
          ></uni-data-select>
        </uni-forms-item>
        <uni-forms-item label="产品名称" name="productName" required>
          <xh-data-select
            v-model="formData.productName"
            :localdata="productList"
            @change="handleChangeProduct"
          ></xh-data-select>
        </uni-forms-item>
        <uni-forms-item
          label="柜号"
          name="cabinetNum"
          v-if="formData.type === '0'"
        >
          <xh-data-select
            v-model="formData.cabinetNum"
            :localdata="cabinetNumList"
            @change="handleChangeCabinet"
          ></xh-data-select>
        </uni-forms-item>
      </uni-forms>
      <uni-section title="明细" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行
					 版样吊瓶: 裁片编号（下拉选择）、数量、结论
					-->
          <uni-tr>
            <uni-th align="center" v-if="formData.type === '0'"
              >裁片编号</uni-th
            >
            <uni-th align="center" v-else>检验编码</uni-th>
            <template v-if="cRole3 || formData.type === '0'">
              <uni-th align="center">数量</uni-th>
              <uni-th align="center">结论</uni-th>
            </template>
            <template v-if="formData.type === '1'">
              <template v-if="cRole1">
                <uni-th align="center">克重</uni-th>
                <uni-th align="center">门幅</uni-th>
              </template>
              <template v-if="cRole2">
                <uni-th align="center">读色数据</uni-th>
                <uni-th align="center">读色结果</uni-th>
              </template>
            </template>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center" v-if="formData.type === '0'">
              {{ item.cuttingCode }}
            </uni-td>
            <uni-td align="center" v-else>
              {{ item.insCode }}
            </uni-td>
            <template v-if="cRole3 || formData.type === '0'">
              <uni-td align="center">{{ item.quantity }}</uni-td>
              <uni-td align="center">{{
                getSelectLabelText2(item.conclusion)
              }}</uni-td>
            </template>

            <template v-if="formData.type === '1'">
              <template v-if="cRole1">
                <uni-td align="center">{{ item.gsm }}</uni-td>
                <uni-td align="center">{{ item.fabricWidth }}</uni-td>
              </template>
              <template v-if="cRole2">
                <uni-td align="center">{{ item.readColorData }}</uni-td>
                <uni-td align="center">{{
                  getSelectLabelText(item.readColorResult)
                }}</uni-td>
              </template>
            </template>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="添加明细"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item
            label="裁片编码"
            name="cuttingCode"
            v-if="formData.type === '0'"
          >
            <xh-data-select
              v-model="detailData.cuttingCode"
              :localdata="cuttingcodeList"
            />
          </uni-forms-item>
          <uni-forms-item v-else label="检验编码" name="insCode">
            <xh-data-select
              v-model="detailData.insCode"
              :localdata="inspectList"
            />
          </uni-forms-item>
          <template v-if="cRole3">
            <uni-forms-item label="数量" name="quantity">
              <uni-easyinput
                type="digit"
                v-model="detailData.quantity"
                placeholder="数量"
              />
            </uni-forms-item>
            <uni-forms-item label="结论" name="conclusion">
              <uni-data-select
                v-model="detailData.conclusion"
                :localdata="conclusionList"
              />
            </uni-forms-item>
          </template>

          <template v-if="formData.type === '1'">
            <template v-if="cRole1">
              <uni-forms-item label="克重" name="gsm">
                <uni-easyinput
                  type="digit"
                  v-model="detailData.gsm"
                  placeholder="请输入克重"
                />
              </uni-forms-item>
              <uni-forms-item label="门幅" name="fabricWidth">
                <uni-easyinput
                  type="digit"
                  v-model="detailData.fabricWidth"
                  placeholder="请输入门幅"
                />
              </uni-forms-item>
            </template>
            <template v-if="cRole2">
              <uni-forms-item label="读色数据" name="readColorData">
                <uni-easyinput
                  type="digit"
                  v-model="detailData.readColorData"
                  placeholder="请输入读色数据"
                />
              </uni-forms-item>
              <uni-forms-item label="读色结果" name="readColorResult">
                <uni-data-select
                  v-model="detailData.readColorResult"
                  :localdata="readColorResultList"
                />
              </uni-forms-item>
            </template>
          </template>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import { BottleTypeEnum } from "@/utils/constant";
import { formatSelectList } from "@/utils/business.js";
import { getRecordBillProduct, getInsCodeList } from "@/api/purchase/fabric.js";
import {
  getBomProductList,
  addBottle,
  getCabinetList,
  getCuttingcodeList,
} from "@/api/purchase/bottleInspect.js";
import {
  getFabricInspectionConclusionDict,
  getBottleInspectionConclusionDict,
} from "@/api/system/dict.js";
import AppStorage from "@/utils/appStorage";
import { Role } from "@/utils/constant";

export default {
  data() {
    return {
      roleKeys: [],
      formData: { type: "0" },
      detailData: {},
      tableData: [],
      typeOptions: BottleTypeEnum,
      inspectList: [],
      productList: [],
      cabinetNumList: [], // 柜号
      conclusionList: [], // 结论
      cuttingcodeList: [], // 裁片编码
      readColorResultList: [
        { text: "不通过", value: "0" },
        { text: "通过", value: "1" },
      ],
      rules1: {
        inspectDate: {
          rules: [
            {
              required: true,
              errorMessage: "请选择检验日期",
            },
          ],
        },
        type: {
          rules: [
            {
              required: true,
              errorMessage: "请选择检验类型",
            },
          ],
        },
        productName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品名称",
            },
          ],
        },
      },
      rules2: {},
    };
  },
  computed: {
    cRole1() {
      return (
        this.roleKeys.includes(Role.fabricInspector1) ||
        this.roleKeys.includes(Role.admin)
      );
    },
    cRole2() {
      return (
        this.roleKeys.includes(Role.fabricInspector2) ||
        this.roleKeys.includes(Role.admin)
      );
    },
    cRole3() {
      return (
        this.roleKeys.includes(Role.fabricBottleInspector) ||
        this.roleKeys.includes(Role.admin) ||
        this.formData.type === "0"
      );
    },
  },
  created() {
    this.fetchProductList();
  },
  mounted() {
    const userInfo = AppStorage.get("userInfo");
    this.roleKeys = userInfo.roleKeys;
  },
  methods: {
    handleChangeCabinet(item) {
      const { value } = item;
      const { productName } = this.formData;
      getCuttingcodeList({
        productName,
        cabinetNum: value,
      }).then((res) => {
        const { rows } = res;
        this.cuttingcodeList = formatSelectList(rows);
      });
    },
    getSelectLabelText(value) {
      return this.readColorResultList.find((item) => item.value === value)
        ?.text;
    },
    getSelectLabelText2(value) {
      return this.conclusionList.find((item) => item.dictValue === value)
        ?.dictLabel;
    },
    // 请求柜号数据
    fetchCabinetList() {
      const { productName } = this.formData;
      getCabinetList({
        productName,
      }).then((res) => {
        const { rows } = res;
        this.cabinetNumList = formatSelectList(rows);
      });
    },
    fetchProductList() {
      const { type } = this.formData;
      if (type === "0") {
        getBomProductList().then((res) => {
          const { rows } = res;
          this.productList = formatSelectList(rows, "productName");
        });
      } else {
        getRecordBillProduct({
          bottlesResult: "0",
          category: "001",
        }).then((res) => {
          const { rows } = res;
          this.productList = formatSelectList(rows, "productName");
        });
      }
    },
    // 请求检验编码数据
    fetchInsCodeList() {
      const { productName } = this.formData;
      if (productName) {
        getInsCodeList(productName, "0").then((res) => {
          const { rows } = res;
          this.inspectList = formatSelectList(rows, "insCode");
        });
      }
    },
    handleChangeProduct(item) {
      const { cabinetNum } = item;
      this.formData.cabinetNum = cabinetNum;
      if (this.formData.type === "0") {
        this.fetchCabinetList();
      }
    },
    handleChangeType() {
      this.fetchProductList();
    },
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
    },
    // 选择检验编码时
    onChangeInsCode(item) {
      const {
        insCode,
        fabricId,
        auditStatus,
        factory,
        boundType,
        balanceMeters,
        balanceVolumeNum,
        validateData,
      } = item;
      this.detailData = {
        ...this.detailData,
        fabricId: fabricId,
        meters: balanceMeters,
        volumeNum: balanceVolumeNum,
        insCode,
        auditStatus,
        factory,
        boundType,
        validateData,
      };
    },
    // 删除
    handelClickDel(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then((values) => {
          const params = {
            ...values,
            itemList: this.tableData,
          };
          addBottle(params).then(() => {
            this.$modal.msgSuccess("新增成功！");
            this.clearData();
            this.$nav.navigateBack();
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    formatSelectOptions(arr) {
      return arr?.map((item) => ({
        ...item,
        text: item.insCode,
        value: item.insCode,
      }));
    },
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          const { type } = this.formData;
          if (
            type === "0" &&
            // cuttingCode
            this.tableData.find(
              (item) => item.cuttingCode === this.detailData.cuttingCode
            )
          ) {
            this.$modal.msgError("裁片编码不能重复");
            return;
          }
          if (
            type === "1" &&
            this.tableData.find(
              (item) => item.insCode === this.detailData.insCode
            )
          ) {
            this.$modal.msgError("检验编码不能重复");
            return;
          }
          this.tableData.push(this.detailData);
          this.detailData = {};
          this.$refs.xhPopup.close();
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    fetchConclusionDict1() {
      getFabricInspectionConclusionDict().then((res) => {
        const { data } = res;
        this.conclusionList = formatSelectList(data, {
          text: "dictLabel",
          value: "dictValue",
        });
      });
    },
    fetchConclusionDict0() {
      getBottleInspectionConclusionDict().then((res) => {
        const { data } = res;
        this.conclusionList = formatSelectList(data, {
          text: "dictLabel",
          value: "dictValue",
        });
      });
    },
    // 添加
    handelClickAdd() {
      this.$refs.form1.validate().then(() => {
        this.$refs.xhPopup.open("top");
        const { type } = this.formData;
        if (type === "1") {
          this.fetchInsCodeList();
          this.fetchConclusionDict1();
        } else {
          this.fetchConclusionDict0();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}
</style>
